<template>
  <el-dialog
    v-model="dialogVisible"
    title="物流信息"
    width="80%"
    :before-close="handleClose"
  >
    <div class="delivery-info">
      <div class="address-info">
        <div class="address-item">
          <h3>发货地址</h3>
          <p>{{ shippingAddress }}</p>
        </div>
        <div class="address-item">
          <h3>收货地址</h3>
          <p>{{ deliveryAddress }}</p>
        </div>
      </div>
      <div id="delivery-map" class="map-container"></div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  shippingAddress: {
    type: String,
    required: true
  },
  deliveryAddress: {
    type: String,
    required: true
  }
})

const emit = defineEmits(['update:visible'])

const dialogVisible = ref(false)
let map = null

watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal
  if (newVal) {
    // 在弹窗显示后初始化地图
    setTimeout(() => {
      initMap()
    }, 100)
  }
})

watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal)
})

const handleClose = () => {
  dialogVisible.value = false
  if (map) {
    map.destroy()
    map = null
  }
}

const initMap = async () => {
  try {
    console.log('开始加载地图...')
    
    // 加载高德地图
    const AMap = await AMapLoader.load({
      key: 'aad7a429816d1c71e51b01d2a525f7e5',
      version: '2.0',
      plugins: ['AMap.Geocoder', 'AMap.Marker', 'AMap.Polyline']
    })
    console.log('地图SDK加载成功')

    // 创建地图实例
    map = new AMap.Map('delivery-map', {
      zoom: 4,
      center: [104.114129, 37.550339],
      viewMode: '2D'
    })
    console.log('地图实例创建成功')

    // 创建地理编码实例
    const geocoder = new AMap.Geocoder({
      city: "全国",
      radius: 1000
    })

    // 创建标记数组
    const markers = []
    const positions = []

    // 使用固定的发货地址坐标（更精确的坐标）
    const shippingPosition = [119.007, 25.431]
    positions.push(shippingPosition)
    
    // 添加发货地址标记
    const shippingMarker = new AMap.Marker({
      position: shippingPosition,
      map: map,
      icon: new AMap.Icon({
        size: new AMap.Size(40, 50),
        image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png',
        imageSize: new AMap.Size(40, 50),
        imageOffset: new AMap.Pixel(0, 0)
      }),
      offset: new AMap.Pixel(-20, -50),
      title: '发货地址'
    })
    markers.push(shippingMarker)

    // 处理收货地址
    if (props.deliveryAddress && props.deliveryAddress !== '暂无收货地址') {
      try {
        const deliveryResult = await new Promise((resolve, reject) => {
          geocoder.getLocation(props.deliveryAddress, (status, result) => {
            if (status === 'complete' && result.info === 'OK') {
              resolve(result)
            } else {
              reject(new Error('收货地址地理编码失败'))
            }
          })
        })

        if (deliveryResult.geocodes && deliveryResult.geocodes.length > 0) {
          const location = deliveryResult.geocodes[0].location
          positions.push([location.lng, location.lat])
          
          // 添加收货地址标记
          const deliveryMarker = new AMap.Marker({
            position: [location.lng, location.lat],
            map: map,
            icon: new AMap.Icon({
              size: new AMap.Size(40, 50),
              image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
              imageSize: new AMap.Size(40, 50),
              imageOffset: new AMap.Pixel(0, 0)
            }),
            offset: new AMap.Pixel(-20, -50),
            title: '收货地址'
          })
          markers.push(deliveryMarker)

          // 如果有两个位置，绘制连线
          if (positions.length === 2) {
            // 创建折线实例
            const polyline = new AMap.Polyline({
              path: positions,
              strokeColor: '#3366FF',
              strokeWeight: 5,
              strokeStyle: 'solid',
              strokeDasharray: [10, 5],
              showDir: true,
              dirColor: '#3366FF',
              map: map
            })

            // 调整地图视野以包含所有标记
            map.setFitView(markers)
          }
        }
      } catch (error) {
        console.error('收货地址地理编码失败:', error)
        // 如果收货地址地理编码失败，只显示发货地址
        map.setCenter(shippingPosition)
        map.setZoom(10)
      }
    } else {
      // 如果没有收货地址，只显示发货地址
      map.setCenter(shippingPosition)
      map.setZoom(10)
    }

  } catch (error) {
    console.error('地图加载失败:', error)
  }
}
</script>

<style scoped>
.delivery-info {
  padding: 20px;
}

.address-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.address-item {
  flex: 1;
  padding: 0 15px;
}

.address-item h3 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 16px;
}

.address-item p {
  margin: 0;
  color: #666;
  font-size: 14px;
  line-height: 1.5;
}

.map-container {
  width: 100%;
  height: 500px;
  border: 1px solid #ccc;
  border-radius: 8px;
  overflow: hidden;
}
</style> 